<template>
  <div class="app-container">
    <!--返回上一步-->
    <div class="back-bar-box mb-30">
      <div class="btn-back" @click="$router.go(-1)"><i class="el-icon-back"></i> 返回</div>
      <div class="line"></div>
      <div class="name">{{$route.name}}</div>
    </div>

    <el-form label-width="120px" :model="article" :rules="rules" ref="article">
      <el-form-item label="分类" prop="categoryId">
        <el-select
          v-model="article.categoryId"
          filterable
          placeholder="请选择" >
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
        </el-select>

        <el-link @click="$router.push('/article/category')" type="primary">分类管理</el-link>

      </el-form-item>

      <el-form-item label="标题" prop="title">
        <el-input v-model="article.title" style="width: 400px"/>
      </el-form-item>

      <el-form-item label="封面">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="BASE_URL+'/eduoss/fileoss?host=article'"
          class="avatar-uploader">
          <img v-if="article.coverImage" :src="article.coverImage" style="width: 200px">
          <el-button type="primary" v-else>上传<i class="el-icon-upload el-icon--right"></i></el-button>
        </el-upload>
      </el-form-item>

      <el-form-item label="图文作者">
        <el-select
          v-model="article.teacherId"
          filterable
          placeholder="请选择">
          <el-option
            v-for="item in teacherList"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
        </el-select>
      </el-form-item>


      <el-form-item label="编辑器">
        <el-radio v-model="article.markdown" :label=false>富文本</el-radio>
        <el-radio v-model="article.markdown" :label=true>makerDown</el-radio>
      </el-form-item>

      <el-form-item label="文章内容">
        <mavon-editor v-if="article.markdown" v-model="article.content" ref=md @imgAdd="imgAdd"
                      @imgDel="" style="height: 500px;"></mavon-editor>
        <tinymce v-else-if="!article.markdown"  :height="300" v-model="article.content"/>

      </el-form-item>
      <div class="bottom-menus">
        <div class="bottom-menus-box">
          <el-button @click="update('article')" type="primary">
            保存
          </el-button>

          <el-button @click="$router.replace('/article')">
            取消
          </el-button>
        </div>
      </div>

    </el-form>
  </div>
</template>
<script>
  import Tinymce from '@/components/Tinymce' //富文本组件
  export default {
    data() {
      return {
        isMarkdown: true,//tinymce/mavon
        value: '',
        article: {
          markdown: true
        },
        teacherList: [],
        categoryList: [],
        BASE_URL: process.env.BASE_URL,//获取dev.env.js中的BASE_API
        rules: {
          title: [
            {required: true, message: '请输入标题', trigger: 'blur'},
            {min: 5, max: 255, message: '长度在 5 到 255 个字符', trigger: 'blur'}
          ],
          categoryId: [
            {required: true, message: '请选择分类', trigger: 'change'}
          ],

        }
      }
    },
    components: {Tinymce},
    created() {
      let id = this.$route.params.id
      if (id) {
        this.getData(id)
      }
      this.getArticleCategory()
      this.getTeacherList()
    },
    methods: {
      getData(id) {
        this.api({
          url: `/article/getArticle/${id}`,
          method: 'get',
        }).then(data => {
          this.article = data
        })
      },
      getArticleCategory() {
        this.api({
          url: `/article/getArticleCategory`,
          method: 'get',
        }).then(data => {
          this.categoryList = data
        })
      },
      getTeacherList() {
        this.api({
          url: `/teacher/findAll`,
          method: 'get'
        }).then(data => {
          this.teacherList = data
        })
      },
      imgAdd(pos, $file) {
        const formData = new FormData()
        formData.append('file', $file)
        formData.append('host', 'article')
        this.api({
          url: `/eduoss/fileoss`,
          method: 'post',
          data: formData
        }).then(res => {
          console.log(res)
          // 放到markdown编辑器内容当中
          this.$refs.md.$img2Url(pos, res)
        })
      },
      handleAvatarSuccess(res, file) {
        this.article.coverImage = res.info
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2
        const typeArr=['image/jpeg','image/png','image/jpg']
        const isImage=typeArr.find(x=>x===file.type);
        if (!isImage) {
          this.$message.error('不支持上传此文件类型!')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!')
        }
        return isImage && isLt2M
      },
      update(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.api({
              url: "/article/updateArticle",
              method: "post",
              data: this.article
            }).then(() => {
              this.$router.replace('/article')
              return this.$message({
                type: 'success',
                message: '修改成功!'
              });
            })
          } else {
            return false;
          }
        });

      }
    }
  }
</script>
<style scoped>
  .el-affix {
    transform: translateY(-110.1406px);
    position: fixed;
    bottom: 20px;
    z-index: 2000;
  }
</style>
